package net.gyapp.markim.module.contact;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.easyder.wrapper.base.view.WrapperSwipeActivity;
import com.easyder.wrapper.core.manager.ImageManager;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.scheduler.Task;
import com.easyder.wrapper.core.scheduler.TaskScheduler;
import com.easyder.wrapper.utils.LogUtils;
import com.joooonho.SelectableRoundedImageView;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.ImPrivateUtils;
import net.gyapp.markim.core.entity.ConversationEntity;
import net.gyapp.markim.core.entity.MemberEntity;
import net.gyapp.markim.dao.DBManager;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.event.AccountChanged;
import net.gyapp.markim.module.basic.event.AccountIml;
import net.gyapp.markim.module.contact.vo.UserVo;
import net.gyapp.markim.utils.RequestParams;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import me.winds.widget.usage.TitleView;

/**
 * Author:  winds
 * Data:    2018/8/22
 * Version: 1.0
 * Desc:
 */


public class UserDetailsActivity extends WrapperSwipeActivity<CommonPresenter> {
    ConversationEntity conversation;
    @BindView(R.id.iv_header)
    SelectableRoundedImageView ivHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_grade)
    ImageView ivGrade;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.iv_msg_switcher)
    ImageView ivMsgSwitcher;
    @BindView(R.id.iv_collect_switcher)
    ImageView ivCollectSwitcher;

    public static Intent getIntent(Context context, ConversationEntity conversation) {
        return new Intent(context, UserDetailsActivity.class).putExtra("conversation", conversation);
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_user_details;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        conversation = (ConversationEntity) intent.getSerializableExtra("conversation");
        ImageManager.load(mActivity, ivHeader, conversation.avatar, R.drawable.placeholder_header);

        MemberEntity entity = ImHelper.queryMemberEntity(conversation.sessionIdStr);
        if (entity != null && !TextUtils.isEmpty(entity.remark)) {
            conversation.name = entity.remark;
        }
        tvName.setText(TextUtils.isEmpty(conversation.name) ? conversation.sessionIdStr : conversation.name);

        tvId.setText(String.format("%1$s%2$s", "ID：", conversation.sessionIdStr));
        String s = tvName.getText().toString();
        if (TextUtils.isEmpty(s)) {
            tvName.setText("暂无昵称");
        }
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        searchContact(conversation.sessionIdStr);
    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        if (url.contains(ApiConfig.API_COLLECTION)) {
            ivCollectSwitcher.setSelected(true);
        } else if (url.contains(ApiConfig.API_CANCEL_COLLECTION)) {
            ivCollectSwitcher.setSelected(false);
        } else if (url.contains(ApiConfig.API_GET_USER_INFO)) {
            processUserInfo((UserVo) dataVo);
        }
    }


    @OnClick({R.id.layout_clear_cache, R.id.btn_confirm, R.id.iv_msg_switcher, R.id.iv_collect_switcher, R.id.layout_info})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_clear_cache:
                clearCache(conversation.id);
                break;
            case R.id.btn_confirm:

                break;
            case R.id.iv_msg_switcher:

                break;
            case R.id.layout_info:
                if (conversation != null) {
                    MemberEntity entity = ImHelper.queryMemberEntity(conversation.sessionIdStr);
                    if (entity == null) {
                        entity = new MemberEntity();
                        entity.name = conversation.latestName;
                        entity.nick = conversation.latestNick;
                        entity.remark = conversation.latestRemark;
                        entity.avatar = conversation.latestAvatar;
                        entity.memberId = conversation.sessionIdStr;
                        entity.userId = conversation.userId;
                    }
                    startActivity(InfoSetActivity.getIntent(mActivity, entity));
                }
                break;
            case R.id.iv_collect_switcher:
                boolean selected = ivCollectSwitcher.isSelected();
                if (selected) {
                    cancelCollect(conversation.sessionIdStr);
                } else {
                    collectUser(conversation.sessionIdStr);
                }
                break;
        }
    }

    private void clearCache(final long conversationId) {
        showLoadingView();
        TaskScheduler.execute(new Task<Boolean>() {
            @Override
            public Boolean doInBackground() throws InterruptedException {
                ImHelper.deleteMessageEntity(conversationId);
                return true;
            }

            @Override
            public void onSuccess(Boolean result) {
                onStopLoading();
                showToast("清除成功");
            }
        });
    }

    private void collectUser(String userId) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_COLLECTION, new RequestParams()
                .put("collectionId", userId)
                .put("type", 2)
                .get(), BaseVo.class);
    }

    private void cancelCollect(String userId) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_CANCEL_COLLECTION,
                new RequestParams()
                        .put("collectionId", userId)
                        .get(),
                BaseVo.class);
    }

    private void searchContact(String s) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_GET_USER_INFO, new RequestParams().put("userName", s).get(), UserVo.class);
    }


    private void processUserInfo(final UserVo dataVo) {
        ImageManager.load(mActivity, ivHeader, dataVo.userInfo.userAvatar, R.drawable.placeholder_header);
        if (TextUtils.isEmpty(dataVo.userInfo.remark)) {
            tvName.setText(TextUtils.isEmpty(dataVo.userInfo.nick) ? dataVo.userInfo.nick : dataVo.userInfo.userName);
            conversation.name = dataVo.userInfo.nick;
        } else {
            tvName.setText(dataVo.userInfo.remark);
            conversation.name = dataVo.userInfo.remark;
        }
        tvId.setText(String.format("%1$s%2$s", "ID：", conversation.sessionIdStr));
        String s = tvName.getText().toString();
        if (TextUtils.isEmpty(s)) {
            tvName.setText("暂无昵称");
        }


        conversation.avatar = dataVo.userInfo.userAvatar;
        TaskScheduler.execute(new Runnable() {
            @Override
            public void run() {
                DBManager.newInstance().getDaoSession().getConversationEntityDao().updateInTx(conversation);
                ImPrivateUtils.updateGroupName(conversation, conversation.name, dataVo.userInfo.userAvatar);
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void accountChanged(AccountChanged changed) {
        if (changed.sign == AccountIml.ACCOUNT_CONTACT_INFO_CHANGED) {
            if (conversation != null) {
                MemberEntity entity = ImHelper.queryMemberEntity(conversation.sessionIdStr);
                if (entity != null && !TextUtils.isEmpty(entity.remark)) {
                    conversation.name = entity.remark;
                    tvName.setText(entity.remark);
                }
            }
        }
    }


}
